import { getProfileAPI } from "./apis/user"
import router from "./router"
import { useUserStore } from "./stores/user"
import { getLocalToken } from "./utils/auth"

const WHITE_LIST = ['/login', '404']

 /**
 * 处理一级路由数据
 */
const getFirstRoutePerms = (permsArr: string[]) => {
  const newArr = permsArr.map(item => {
    return item.split(':')[0]
  })
  return [...new Set(newArr)]
}

// 处理二级路由权限数据
const getSecondRoutePerms = (permsArr: string[]) => {
  const newArr = permsArr.map(item => {
    const arr = item.split(':')
    return `${arr[0]}:${arr[1]}`
  })
  return [...new Set(newArr)]
}



router.beforeEach(async (to, from, next) => { 
  const token = getLocalToken()
  // 有Token
  if (token) {
    next()

    const store = useUserStore()

    if (!store.profile.id) {
      const res = await getProfileAPI()
      // console.log(res);
      // 设置用户信息
      store.setProfile(res.data)
      console.log(res.data.permissions);
      // 设置一级路由权限
      const firstRouterPers = getFirstRoutePerms(res.data.permissions)
      console.log(firstRouterPers);
      // 设置二级路由权限
      const secondRouterPers = getFirstRoutePerms(res.data.permissions)
      console.log(secondRouterPers);
    }
    
  } else {
    // 如果没有Token
    if (WHITE_LIST.includes(to.path)) {
      next()
    } else {
      next('login')
    }
  }

 
})
